#! /bin/sh

. /etc/utils.sh

# called from ifplugd

iface="$1"
action="$2"

CONMAN_STATUS_DIR=/tmp/conman/interfaces

echo "ifplugd: $iface is $action"

case "$action" in
  up)
    # Clear any existing dynamic IP config.
    rm -f "/tmp/ip/dynamic/$iface"

    # Update ipv4 address on $iface
    ipapply "$iface"

    if [ "$iface" = pon0 ]; then
      # Fiber Jack
      ethtool -r eth0
      ifup man
    fi
    if is-spacecast && [ "$iface" = lan0 ]; then
      # Spacecast Box
      run-dhclient "$iface"
    fi
    if [ "$iface" = wan0 ]; then
      # Network Box
      # Start dhclient on the wan interfaces.
      run-dhclient "$iface"
      if interface_exists wan0.2; then
        run-dhclient wan0.2
      fi

      if [ -e "/sys/class/net/br0" ]; then
        # Stop any running dhclients on br0 now that the wan is up.
        killpid /var/run/dhclient.br0.pid
        killpid /var/run/dhclient6.br0.pid

        # Bridge mode might require br0 to switch address config.
        ipapply br0
      fi
    fi
    if is-wireless-client; then
      echo 1 >"$CONMAN_STATUS_DIR/$iface"

      if [ "$iface" = eth0 ] || [ "$iface" = moca0 ]; then
        run-dhclient br0
      elif startswith "$iface" wcli; then
        run-dhclient "$iface"
      fi
    fi

    QUIET=1 restart dnsmasq
    ;;
  down)
    # Update ipv4 address on $iface
    ipapply "$iface"

    if [ "$iface" = pon0 ]; then
      ethtool -r eth0
    fi
    if is-wireless-client; then
      echo 0 >"$CONMAN_STATUS_DIR/$iface"
    fi
    if [ "$iface" = "wan0" -a -e /sys/class/net/br0 ]; then
      # Run dhclient for bridge mode, ipapply will select the
      # appropriate configuration (static vs dynamic).
      ipapply br0
      run-dhclient br0
    fi

    QUIET=1 restart dnsmasq
    ;;
  *)
    echo "$0: unknown action '$action'"
    exit 1
esac
exit 0
